package ws;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import model.No;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class OpenStreetMap {
	
	private static final String OVERPASS_API = "http://www.overpass-api.de/api/interpreter?data=";
	
	public List<String> getNodes(String street){
		String url = "way['name'~'"+street+"'](-3.857,-38.654,-3.703,-38.379);out;";
		try {
			url = URLEncoder.encode(url,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Client c = Client.create();
		WebResource wr = c.resource(OVERPASS_API+url);
		ClientResponse cr = wr.accept("text/xml").get(ClientResponse.class);
		Document doc  = cr.getEntity(Document.class);
		NodeList nl = doc.getElementsByTagName("nd");
		List<String> nodes = new ArrayList<String>();
		for(int i=0;i<nl.getLength();i++){
			nodes.add(nl.item(i).getAttributes().item(0).getNodeValue());
		}
		return nodes;
	}
	
	public No getInstersectNode(String street1 , String street2){
		List<String> nodesS1 = getNodes(street1);
		List<String> nodesS2 = getNodes(street2);
		for(String s :  nodesS2){
			if(nodesS1.contains(s))
				return getInfoNode(s);
		}
		return null;
	}
	
	public No getInfoNode(String node){
		No n = null;
		String url = "node("+node+");out;";
		Client c = Client.create();
		WebResource wr = c.resource(OVERPASS_API+url);
		ClientResponse cr = wr.accept("text/xml").get(ClientResponse.class);
		Document doc  = cr.getEntity(Document.class);
		NodeList nl = doc.getElementsByTagName("node");
		if(nl!=null){
			n = new No();
			n.setId(nl.item(0).getAttributes().item(0).getNodeValue());
			n.setLat(nl.item(0).getAttributes().item(1).getNodeValue());
			n.setLon(nl.item(0).getAttributes().item(2).getNodeValue());
		}
		return n;
	}
	
	public static void main(String args[]){
		OpenStreetMap osm = new OpenStreetMap();
		String street1 = "Avenida 13 de Maio";
		String street2 = "Rua da Assunção";
		No n = osm.getInstersectNode(street1, street2);
		System.out.println("Id:"+n.getId()+" lat:"+n.getLat()+" lon:"+n.getLon());
//		System.out.println(osm.getInstersectNode(street1, street2));
//		osm.getNodes(street);
//		System.out.println("---------------------------------------");
//		osm.getNodes(street2);
	}

}
